/**
 * 指数K线数据钩子
 */

import { useQuery } from '@tanstack/react-query';
import { get } from '@shared/utils/apiClient';
import { ApiResponse, IndexBarsResponse, BarPeriod } from '@shared/types/market';

const API_BASE = import.meta.env.VITE_API_BASE_URL || '';

interface UseIndexBarsOptions {
  code: string;
  period?: BarPeriod;
  start?: string;
  end?: string;
  limit?: number;
}

/**
 * 获取指数K线数据
 */
export function useIndexBars({
  code,
  period = '5m',
  start,
  end,
  limit = 500,
}: UseIndexBarsOptions) {
  return useQuery({
    queryKey: ['indexBars', code, period, start, end, limit],
    queryFn: async () => {
      const params = new URLSearchParams({
        code,
        period,
        limit: limit.toString(),
      });

      if (start) params.append('start', start);
      if (end) params.append('end', end);

      const response = await get<ApiResponse<IndexBarsResponse>>(
        `${API_BASE}/api/v1/market/index-bars?${params.toString()}`
      );
      return response.data;
    },
    staleTime: period === '5m' || period === '1m' ? 30000 : 300000, // 分时数据缓存30秒，历史数据缓存5分钟
    gcTime: 600000, // 缓存10分钟
    refetchOnWindowFocus: false,
    enabled: !!code, // 只有当code存在时才启用
  });
}

